package com.framework.test.filters;

import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.Reporter;

public class LogFilter implements Filter {

    private final Logger logger = LogManager.getLogger(LogFilter.class);

    @Override
    public Response filter(FilterableRequestSpecification requestSpec,
                           FilterableResponseSpecification responseSpec,
                           FilterContext filterContext) {

        StringBuilder requestLog = new StringBuilder("\n==== REQUEST DETAILS ====");
        requestLog.append("<br/>Request Method: ").append(requestSpec.getMethod());
        requestLog.append("<br/>Request URL: ").append(requestSpec.getURI());

        requestLog.append("<br/>Request Headers: ");
        requestSpec.getHeaders().forEach(header ->
                requestLog.append("<br/>  ").append(header.getName()).append(": ").append(header.getValue())
        );

        if (!requestSpec.getQueryParams().isEmpty()) {
            requestLog.append("<br/>Request Query Parameters: ");
            requestSpec.getQueryParams().forEach((name, value) ->
                    requestLog.append("<br/>  ").append(name).append(": ").append(value)
            );
        }

        if (requestSpec.getBody() != null) {
            requestLog.append("<br/>Request Body: ").append(requestSpec.getBody().toString());
        }

        Response response = filterContext.next(requestSpec, responseSpec);

        StringBuilder responseLog = new StringBuilder("\n==== RESPONSE DETAILS ====");
        responseLog.append("<br/>Response Status: ").append(response.getStatusCode()).append(" ").append(response.getStatusLine());
        responseLog.append("<br/>Response Time: ").append(response.getTime()).append(" ms");

        responseLog.append("<br/>Response Headers: ");
        response.getHeaders().forEach(header ->
                responseLog.append("<br/>  ").append(header.getName()).append(": ").append(header.getValue())
        );

        responseLog.append("<br/>Response Body: ").append(response.getBody().asString());

        // 记录到ExtentReport中
        Reporter.log(requestLog.toString());
        Reporter.log(responseLog.toString());
        String reqLog = requestLog.toString().replace("<br/>", "\n");
        String resLog = responseLog.toString().replace("<br/>", "\n");
        logger.info(reqLog);
        logger.info(resLog);

        return response;
    }
}